class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        int i = 0, j = 1;
        int pos = 0;
        int n = nums.size();
        while (1) {
            while (j < n && nums[j] == nums[j - 1]) {
                ++j;
            }
            nums[pos++] = nums[j - 1];
            if (j - i >= 2) {
                nums[pos++] = nums[j - 1];
            }
            if (j == n)
                break;
            i = j;
            ++j;
        }
        int k = n - pos;
        while (k--)
            nums.pop_back();
        return pos;
    }
};